/**
 * 整合websocket
 */
let logger = coreLogger.getLogger("common")("websocket");
let _reconnect = 0;
let _promise = null;
let _socket = null;
let _socketReady = false;
let aioWebsocket = null;
let messageCallback = Noop;

export default class AioWebsocket {
  static getinstance() {
    if (aioWebsocket === null || !_socketReady) {
      aioWebsocket = new AioWebsocket();
    }
    return aioWebsocket;
  }
  static setMessageCallback = callback => {
    messageCallback = callback;
  }
  constructor() {
    if (_promise && _socket && _socket.readyState === 0) {
      logger.debug("aioWebsocket is connecting");
      return _promise;
    }
    _promise = new Promise((resolve, reject) => {
      let connectSocket = () => {
        if (_socket && _socket.readyState === 1) {
          // 已经建立连接，则直接使用
          resolve(this);
        } else {
          // 未建立连接，则等待建立连接
          _socket = new WebSocket(`ws://localhost:${window.CLIENTCONFIG.TUP_PORT || "7683"}`, "tup_service_protocol");
          _socket.addToInitCollect("aio", this.releaseWebSocket, _socket);
          // 确保连接可用和连接成功回调
          // ToDo...
          // 连接关闭回调
          _socket.onclose = () => {
            // 不同tup模块有差异性
            this.releaseWebSocket();
          };
          _socket.onerror = () => {
            _socketReady = false;
            if (_reconnect < 15) {
              _reconnect++;
              setTimeout(function () {
                connectSocket();
              }, 300);
            } else {
              reject(this);
              _socket = null;
            }
          };

          _socket.onopen = () => {
            logger.info("aioWebsocket open!!");
            _reconnect = 0;

            // 解决UI刷新但是Tup不重启的问题
            setTimeout(() => {
              _socketReady = true;
              resolve(this);
            }, 1000);
          };

          // 绑定回调仓库
          _socket.onmessage = msg => {
            try {
              // 不同tup模块有差异性
              let data = JSON.parse(msg.data);
              // 处理通知消息
              messageCallback(data.module_id, data);
            } catch (error) {
              logger.info(' _socket.onmessage is error', error);
            }
          };
        }
      };
      connectSocket();
    });
    return _promise;
  }
  releaseWebSocket() {
    if (_socket) {
      _socket.onopen = null;
      _socket.onclose = null;
      _socket.onerror = null;
      _socket.onmessage = null;
      _socketReady = false;
      _socket = null;
      logger.info("aioWebsocket closed!!");
    }
  }
  sendMessage(data) {
    _socketReady && _socket.sendToTup(data);
  }
}